package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.TaoHuaApi;
import com.tanhua.dubbo.server.pojo.TaoHua;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.TaoHuaVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class TaoHuaService {

    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference(version = "1.0.0")
    private TaoHuaApi taoHuaApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存
     *
     * @param soundFile
     * @return
     */
    public Boolean saveSound(MultipartFile soundFile) {
        //获取线程中的user对象
        User user = UserThreadLocal.get();

        //判断线程中的用户对象是否为空.为空直接返回false
        if (null == user) {
            return false;
        }

        //将今日时间构成年月日的形式
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());                    //放入Date类型数据

        //获取当前时间的年月日
        String date = "" + calendar.get(Calendar.YEAR) + calendar.get(Calendar.MONTH) + calendar.get(Calendar.DATE);

        //获取当前用户今日特有的key
        String key = user.getId().toString() + date + "SEND_TAO_HUA";
        //如果不包含这个特有的key,则将该键对应的值设为10
        if (!this.redisTemplate.hasKey(key)) {
            this.redisTemplate.opsForValue().set(key, "10");
        }
        //如果包含就将值减一
        this.redisTemplate.opsForValue().decrement(key);

        //如果值小于0代表今日的十次机会已经用完,直接返回false
        if (Integer.parseInt(this.redisTemplate.opsForValue().get(key)) < 0) {
            return false;
        }
        //新建桃花对象
        TaoHua taoHua = new TaoHua();

        //给taohua封装对象
        taoHua.setUserId(user.getId().intValue());
        //调用方法获取该用户对应的详细详细
        UserInfo userInfo = this.userInfoService.queryById(user.getId());
        //如果返回的对象为空,代表没有这个用户,同样返回false
        if (null == userInfo) {
            return false;
        }

        taoHua.setAvatar(userInfo.getLogo());
        taoHua.setNickname(userInfo.getNickName());
        taoHua.setGender(userInfo.getSex().name().toLowerCase());
        taoHua.setAge(userInfo.getAge().toString());

        //获取语音地址
        //上传语音
        StorePath storePath = null;
        try {
            storePath = storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StringUtils.substringAfter(soundFile.getOriginalFilename(), "."),
                    null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置语音地址
        taoHua.setSoundUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath());

        //调用double中的方法将对象存入mongoDb中
        return this.taoHuaApi.saveSound(taoHua);
    }




    public TaoHuaVo findSound() {
        User user = UserThreadLocal.get();
        if (null == user) {
            return null;
        }

        TaoHuaVo taoHuaVo = new TaoHuaVo();

        //将今日时间构成年月日的形式
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());                    //放入Date类型数据

        //获取当前时间的年月日
        String date = "" + calendar.get(Calendar.YEAR) + calendar.get(Calendar.MONTH) + calendar.get(Calendar.DATE);

        //获取当前用户今日特有的key
        String key = user.getId().toString() + date + "FIND_TAO_HUA";

        //特有的key
        String keyShow = user.getId().toString() + date + "SHOW_TAO_HUA";

        //如果不包含这个特有的key,则将该键对应的值设为10
        if (!this.redisTemplate.hasKey(key)) {
            this.redisTemplate.opsForValue().set(key, "10");
        }

        //如果包含就将值减一
        this.redisTemplate.opsForValue().decrement(key);
        //设置次数
        taoHuaVo.setRemainingTimes(Integer.parseInt(this.redisTemplate.opsForValue().get(key)));

        //如果值小于0代表今日的十次机会已经用完,直接返回false
        if (Integer.parseInt(this.redisTemplate.opsForValue().get(key)) < 0) {
            return null;
        }
        List<TaoHua> taoHuaList = this.taoHuaApi.findSound();

        //去除包含当前用户的语音
        for (int i = 0; i < taoHuaList.size(); i++) {

            if (user.getId().intValue()==taoHuaList.get(i).getUserId()){
                taoHuaList.remove(i);
            }

            if (this.redisTemplate.opsForHash().hasKey(keyShow,taoHuaList.get(i).getId().toHexString())){
                taoHuaList.remove(i);
            }
        }

        if (taoHuaList.isEmpty()){
            return null;
        }

        TaoHua taoHua = taoHuaList.get(RandomUtils.nextInt(0, taoHuaList.size() - 1));
        taoHuaVo.setId(taoHua.getUserId());
        taoHuaVo.setAvatar(taoHua.getAvatar());
        taoHuaVo.setNickname(taoHua.getNickname());
        taoHuaVo.setGender(taoHua.getGender());
        taoHuaVo.setAge(taoHua.getAge());
        taoHuaVo.setSoundUrl(taoHua.getSoundUrl());

        this.redisTemplate.opsForHash().put(keyShow,taoHua.getId().toHexString(),"1");
        return taoHuaVo;

    }
}
